<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属站点" prop="stationIdC">
        <el-select v-model="queryParams.stationIdC" @change="stationOptionChange" placeholder="请选择站点" clearable filterable>
          <el-option
            v-for="item in stationOptions"
            :key="item.stationIdC"
            :label="item.stationName + ',' + item.stationIdC"
            :value="item.stationIdC">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="历史设备" prop="equipHistoryId">
        <el-select v-model="queryParams.equipHistoryId" placeholder="请选择历史设备" clearable filterable>
          <el-option
            v-for="item in equipHistoryOptions"
            :key="item.equipHistoryId"
            :label="item.equipName"
            :value="item.equipHistoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维修编号" prop="repairCode">
        <el-input
          v-model="queryParams.repairCode"
          placeholder="请输入维修单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="repairStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.repairStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择维修开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="repairEndTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.repairEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择维修结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="维修类型" prop="repairTypeId">
        <el-select v-model="queryParams.repairTypeId" placeholder="请选择维修类型" clearable size="small">
          <el-option
            v-for="item in repairTypeOptions"
            :key="item.repairTypeId"
            :label="item.repairTypeName"
            :value="item.repairTypeId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维修状态" prop="repairState">
        <el-select v-model="queryParams.repairState" placeholder="请选择维修单状态" clearable size="small">
          <el-option
            v-for="dict in repairStateOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['modules:repair:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['modules:repair:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['modules:repair:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['modules:repair:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维修ID" align="center" prop="repairId" v-if="false"/>
      <el-table-column label="维修单编号" align="center" prop="repairCode" />
      <el-table-column label="所属站点" align="center" prop="stationIdC">
        <template slot-scope="scope">
          <span>{{ stationName(scope.row.stationIdC) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="历史设备" align="center" prop="equipHistoryId" >
        <template slot-scope="scope">
          <span>{{ equipHistoryName(scope.row.equipHistoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障编号" align="center" prop="faultCode"/>
      <el-table-column label="维修开始时间" align="center" prop="repairStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.repairStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修结束时间" align="center" prop="repairEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.repairEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修结果" align="center" prop="repairResult" />
      <el-table-column label="维修类型" align="center" prop="repairTypeId" >
        <template slot-scope="scope">
          {{ repairTypeName(scope.row.repairTypeId) }}
        </template>
      </el-table-column>
      <el-table-column label="维修单状态" align="center" prop="repairState" >
        <template slot-scope="scope">
          {{ repairStateName(scope.row.repairState) }}
        </template>
      </el-table-column>
      <el-table-column label="维修用户" align="center" prop="repairUserName" />
      <el-table-column label="值班用户" align="center" prop="dutyUserName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['modules:repair:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['modules:repair:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改维修单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body style="padding: 0 20px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
        <el-form-item label="维修单编号" prop="repairCode">
          <el-input v-model="form.repairCode" placeholder="请输入维修单编号" disabled/>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="所属站点" prop="stationIdC">
          <el-select v-model="form.stationIdC" placeholder="请选择站点" @change="stationOptionChange" clearable filterable>
            <el-option
              v-for="item in stationOptions"
              :key="item.stationIdC"
              :label="item.stationName + ',' + item.stationIdC"
              :value="item.stationIdC">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="历史设备" prop="equipHistoryId">
          <el-select v-model="form.equipHistoryId" placeholder="请选择历史设备" @change="equipHistoryOptionChange" clearable filterable>
            <el-option
              v-for="item in equipHistoryOptions"
              :key="item.equipHistoryId"
              :label="item.equipName"
              :value="item.equipHistoryId">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="故障编号" prop="faultId" v-if="form.equipHistoryId !== undefined && form.equipHistoryId !== ''">
          <el-select v-model="form.faultId" placeholder="请选择故障编号">
            <el-option
              v-for="item in faultOptions"
              :key="item.faultId"
              :label="item.faultCode"
              :value="item.faultId">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="维修开始时间" prop="repairStartTime">
          <el-date-picker clearable size="small"
            v-model="form.repairStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择维修开始时间"
                          style="width: 200px">
          </el-date-picker>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="维修结束时间" prop="repairEndTime">
          <el-date-picker clearable size="small"
            v-model="form.repairEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择维修结束时间"
                          style="width: 200px">
          </el-date-picker>
        </el-form-item>
        </el-col>
          <el-row>
            <el-col :span="12">
              <el-form-item label="现场照片">
                <el-upload
                  name="files"
                  ref="uploadSitePhoto"
                  :action="uploadPhotoUrl()"
                  :file-list="sitePhotoUrlList"
                  :auto-upload="true"
                  :before-upload="beforeUploadPhoto"
                  :on-remove="removeSitePhoto"
                  accept="image/jpg,image/jpeg,image/png"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传 jpg/jpeg/png 文件，且不超过 500kb
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        <el-col :span="12">
        <el-form-item label="维修用户" prop="repairUserId">
          <el-select v-model="form.repairUserId" placeholder="请选择维修用户" filterable clearable>
            <el-option
              v-for="dict in allUserOptions"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="值班用户" prop="dutyUserId">
          <el-select v-model="form.dutyUserId" placeholder="请选择值班用户" filterable clearable>
            <el-option
              v-for="dict in allUserOptions"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="维修类型" prop="repairTypeId">
          <el-select v-model="form.repairTypeId" placeholder="请选择维修类型" clearable>
            <el-option
              v-for="item in repairTypeOptions"
              :key="item.repairTypeId"
              :label="item.repairTypeName"
              :value="item.repairTypeId">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="维修状态" prop="repairState">
          <el-select v-model="form.repairState" placeholder="请选择维修单状态">
            <el-option
              v-for="dict in repairStateOptions"
              :key="dict.key"
              :label="dict.value"
              :value="dict.key"
            />
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
        <el-form-item label="维修结果" prop="repairResult">
          <el-input v-model="form.repairResult" placeholder="请输入维修结果" />
        </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="22">
            <el-form-item label="备注">
              <editor v-model="form.remark" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRepair,
  getRepair,
  delRepair,
  addRepair,
  updateRepair,
  exportRepair,
  getRepairCode
} from "@/api/modules/repair";
import Editor from '@/components/Editor';
import {listInfoByDto} from "@/api/modules/info";
import {listStationEquipHistoryOption} from "@/api/modules/equipHistory";
import {listIdAndNickName} from "@/api/system/user";
import {listRepairType} from "@/api/modules/repairType";
import {selectFaultByDto} from "@/api/modules/fault";
import {uploadByParent} from "@/api/modules/upload";

export default {
  name: "Repair",
  components: {
    Editor
  },
  data() {
    return {
      // 删除的照片集合
      deletePhotoList:[],
      // 现场照片集合
      sitePhotoUrlList: [],
      // 所有故障单
      allFaultList:[],
      // 故障选择
      faultOptions:[],
      // 所有用户选择
      allUserOptions:[],
      // 站点所有设备
      allEquipHistory:[],
      // 站点设备选择
      equipHistoryOptions:[],
      // 维修状态
      repairStateOptions:[
        {"key":1,value:'未接单'},
        {"key":2,value:'处理中'},
        {"key":3,value:'提交结果'},
        {"key":4,value:'处理完成'}
      ],
      // 维修类型选择列表
      repairTypeOptions:[],
      // 站点选择列表
      stationOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修单管理表格数据
      repairList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationIdC: undefined,
        equipHistoryId: undefined,
        repairCode: undefined,
        repairStartTime: undefined,
        repairEndTime: undefined,
        repairTypeId: undefined,
        repairState: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    /** 初始化当前页面 */
    init(){
      let selectDto = {
        stationState:1
      };
      listInfoByDto(selectDto).then(res=>{
        this.stationOptions = res.data;
      });
      listIdAndNickName().then(res=>{
        this.allUserOptions = res;
      });
      listRepairType().then(res=>{
        this.repairTypeOptions = res.rows;
      })
      selectFaultByDto().then(res=>{
        this.allFaultList = res.data;
      })
      listStationEquipHistoryOption().then(res=>{
        this.allEquipHistory = res.data;
        this.equipHistoryOptions = res.data;
      })
    },
    /** 上传照片路径 */
    uploadPhotoUrl(){
      return process.env.VUE_APP_BASE_API + "/uploadByPatent?parent=repair"
    },
    /** 上传照片前的操作 */
    beforeUploadPhoto(files){
      let formData = new FormData();
      formData.append("files",files);
      uploadByParent(formData,"repair").then(res=>{
        let resList = res.data;
        if(resList){
          this.sitePhotoUrlList = this.sitePhotoUrlList.concat(resList);
        }
      })
    },
    /** 图片移除 */
    removeSitePhoto(file, fileList){
      // 记录删除的照片
      this.deletePhotoList.push(file);
      // 移除
      this.sitePhotoUrlList = fileList
    },
    /** 获取故障单编号 */
    initRepairCode(){
      getRepairCode().then(res=>{
        this.form.repairCode = res.data.repairCode
      });
    },
    /** 站点下拉框发生变化时 */
    stationOptionChange(stationIdC){
      // 历史设备发生变化
      this.equipHistoryByStationIdC(stationIdC);
      this.form.equipHistoryId = '';
      this.form.faultId = '';
    },
    /** 历史设备下拉框发生变化时 */
    equipHistoryOptionChange(equipHistoryId){
      this.form.faultId = '';
      // 重置下拉框
      this.faultOptions = [];
      this.allFaultList.forEach(fault=>{
        if(fault.equipHistoryId === equipHistoryId){
          this.faultOptions.push(fault);
        }
      })
    },
    /** 根据站点ID查询历史设备 */
    equipHistoryByStationIdC(stationIdC){
      let selectDto = {
        stationIdC:stationIdC
      };
      listStationEquipHistoryOption(selectDto).then(res=>{
        this.equipHistoryOptions = res.data;
      })
    },
    /** 回显维修类型名称 */
    repairTypeName(repairTypeId){
      let value = '';
      this.repairTypeOptions.forEach(repairType =>{
        if(repairType.repairTypeId === repairTypeId){
          value = repairType.repairTypeName;
        }
      });
      return value;
    },
    /** 回显维修状态 */
    repairStateName(key){
      let value = '';
      this.repairStateOptions.forEach(repair =>{
        if(repair.key === key){
          value = repair.value;
        }
      });
      return value;
    },
    /** 回显历史设备名称 */
    equipHistoryName(equipHistoryId){
      let value = '';
      this.allEquipHistory.forEach(equipHistory =>{
        if(equipHistory.equipHistoryId === equipHistoryId){
          value = equipHistory.equipName;
          return value;
        }
      });
      return value;
    },
    /** 回显站点名称 */
    stationName(stationIdC){
      let value = '';
      this.stationOptions.forEach(station =>{
        if(station.stationIdC === stationIdC){
          value = station.stationName + "," + station.stationIdC;
          return value;
        }
      });
      return value;
    },
    /** 查询维修单管理列表 */
    getList() {
      this.loading = true;
      listRepair(this.queryParams).then(response => {
        this.repairList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.sitePhotoUrlList = [];
      this.deletePhotoList = [];
      this.form = {
        repairId: undefined,
        stationIdC: undefined,
        equipHistoryId: undefined,
        repairCode: undefined,
        faultId: undefined,
        repairStartTime: undefined,
        repairEndTime: undefined,
        repairUserId: undefined,
        repairResult: undefined,
        repairTypeId: undefined,
        remark: undefined,
        repairState: undefined,
        dutyUserId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.repairId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修单管理";
      // 初始化维修单编号
      this.initRepairCode();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const repairId = row.repairId || this.ids
      getRepair(repairId).then(response => {
        this.sitePhotoUrlList = response.data.tbaseRepairPhotoList;
        this.form = response.data;
        this.open = true;
        this.title = "修改维修单管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sitePhotoUrlList = this.sitePhotoUrlList;
          this.form.deletePhotoList = this.deletePhotoList;
          if (this.form.repairId != null) {
            updateRepair(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRepair(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const repairIds = row.repairId || this.ids;
      this.$confirm('是否确认删除维修单管理编号为"' + repairIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRepair(repairIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有维修单管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRepair(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
